package com.itheima.controller;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;


import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;
    /**
     * 上传到本地，可上传到云端，阿里云oss等
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R uploadFile( MultipartFile file){
       //上传图片的命名以当前时间命名
        String mimeType=file.getContentType();//图片类型,image/png
        log.info("图片类型：{}",mimeType);
        String suffix="";
        String supportedFormatTable[][]={
                {"image/png",".png"},
                {"image/bmp",".bmp"},
                {"image/jpg",".jpg"},
                {"image/gif",".gif"},
                {"image/jpeg",".jpeg"}
        };
       /* String format="yyyyMMddhhmmss";
        String imgFilePrefix= LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));*/
        String prefix= UUID.randomUUID().toString();
        for (int i = 0; i < supportedFormatTable.length; ++i) {
            if(supportedFormatTable[i][0].equals(mimeType)){
                suffix=supportedFormatTable[i][1];
                break;
            }
        }

        String newImgFileName=prefix+suffix;//图片的命名
        log.info("newImgFileName:{}",newImgFileName);
        String directoryPath=basePath;
        File dir = new File(directoryPath);
        if(!dir.exists()){
            dir.mkdirs();
        }


        try {
            file.transferTo(new File(basePath,newImgFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(newImgFileName);
    }

    @GetMapping("/download")
    public void downloadFile(String name, HttpServletResponse response){
        try {
            String directoryPath=basePath;
            FileInputStream fileInputStream = new FileInputStream(new File(directoryPath, name));
            response.setContentType("image/jpeg");
            ServletOutputStream  outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
